﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.COM;
using System.Threading;
using System.ServiceModel.Web;
using WCFMINERP.BLL.PhotoBll;

namespace WCFMINERP.Services.Files
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true,InstanceContextMode=InstanceContextMode.Single,ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class FilesService : WCFMINERP.Contracts.InterFaces.IFilesService
    {

        PhotoinfoBll infoBll = new PhotoinfoBll();

        System.Web.Caching.Cache CacheData = System.Web.HttpRuntime.Cache;

       // static  = new List<CusFileInfo>();

        #region IFilesService 成员
        public Stream DownloadFileStream(string serverfile, string path)
        {
            CusFileInfo file = null;
           
            List<CusFileInfo> dataList = CacheData.Get("CusFileInfo") as List<CusFileInfo>;
            var enumerator = dataList.Where((t) => t.MapPath == path + "/" + serverfile).GetEnumerator();
            if (enumerator.MoveNext())
            {
               file = enumerator.Current;
            }
            else
            {
                throw new FaultException("非法请求。");
            }
            if (File.Exists(file.filepath))
            {
                var incomingRequest = WebOperationContext.Current.IncomingRequest;
                var outgoingResponse = WebOperationContext.Current.OutgoingResponse;
                long offset = 0, count = file.FileLength;
                if (incomingRequest.Headers.AllKeys.Contains("Range"))
                {
                    var match = System.Text.RegularExpressions.Regex.Match(incomingRequest.Headers["Range"], @"(?<=bytes\b*=)(\d*)-(\d*)");
                    if (match.Success)
                    {
                        outgoingResponse.StatusCode = System.Net.HttpStatusCode.PartialContent;
                        string v1 = match.Groups[1].Value;
                        string v2 = match.Groups[2].Value;
                        if (!match.NextMatch().Success)
                        {
                            if (v1 == "" && v2 != "")
                            {
                                var r2 = long.Parse(v2);
                                offset = count - r2;
                                count = r2;
                            }
                            else if (v1 != "" && v2 == "")
                            {
                                var r1 = long.Parse(v1);
                                offset = r1;
                                count -= r1;
                            }
                            else if (v1 != "" && v2 != "")
                            {
                                var r1 = long.Parse(v1);
                                var r2 = long.Parse(v2);
                                offset = r1;
                                count -= r2 - r1 + 1;
                            }
                            else
                            {
                                outgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                            }
                        }
                    }

                }
                outgoingResponse.ContentType = "application/force-download";
                outgoingResponse.ContentLength = count;

                Console.WriteLine("开始下载：" + serverfile + "(" + offset + "--" + count + ")");
                CusStreamReader fs = new CusStreamReader(new FileStream(file.filepath, FileMode.Open, FileAccess.Read, FileShare.Read), offset, count);
                fs.Reading += (t) =>
                {
                    //限速代码,实际使用时可以去掉，或者精确控制
                    Thread.Sleep(300);
                    Console.WriteLine(t);
                };
                return fs;
            }
            else
            {
                throw new FaultException("没找到文件：" + serverfile);
            }

        }

        public Stream DownloadFileStream(string serverfile, string path,long offset = 0, long count = 0)
        {
            CusFileInfo file = null;
            List<CusFileInfo> dataList = CacheData.Get("CusFileInfo") as List<CusFileInfo>;
            var enumerator = dataList.Where((t) => t.MapPath == path + "/" + serverfile).GetEnumerator();
            if (enumerator.MoveNext())
            {
                file = enumerator.Current;
            }
            else
            {
                throw new FaultException("非法请求。");
            }
            if (offset >= file.FileLength)
            {
                throw new FaultException("请求的断点超过了文件最大长度。");
            }
            if (count == 0)
            {
                count = file.FileLength - offset;
            }
            if (File.Exists(file.filepath))
            {
                var outgoingResponse = WebOperationContext.Current.OutgoingResponse;
                outgoingResponse.ContentType = "application/force-download";

                Console.WriteLine("开始下载：" + serverfile + "(" + offset + "--" + count + ")");
                CusStreamReader fs = new CusStreamReader(new FileStream(file.filepath, FileMode.Open, FileAccess.Read, FileShare.Read), offset, count);
                fs.Reading += (t) =>
                {
                    //限速代码,实际使用时可以去掉，或者精确控制
                    //Thread.Sleep(300);
                    //Console.WriteLine(t);
                };              
                return fs;
            }
            else
            {
                throw new FaultException("没找到文件：" + serverfile);
            }
        }

        /// <summary>
        /// 获取下载目录
        /// </summary>
        /// <returns></returns>        
        public List<CusFileInfo> GetFiles(string outshopid)
        {
            WriteAnalyseLog.WriteLogFile(DateTime.Now + ":开始获取数据");
            if (string.IsNullOrEmpty(outshopid))
            {
                return null; //"请传入有效商户ID";
            }
            int a = 0;
            if (int.TryParse(outshopid, out a) == false) //判断是否可以转换为整型
            {
                return null; //"商户ID为数字";
            }
            int shopid = Convert.ToInt32(outshopid);

            List<CusFileInfo>  fileinfolist = infoBll.GetFileInfo(shopid);

            if (CacheData == null || CacheData.Count==0)
            {
                if (CacheData["CusFileInfo"] == null)
                {
                    CacheData.Insert("CusFileInfo", fileinfolist);
                }
            }
            else
            {
                List<CusFileInfo> dataList = CacheData.Get("CusFileInfo") as List<CusFileInfo>;
                foreach (CusFileInfo info in fileinfolist)
                {
                    if (!dataList.Any(p => p.Photoid == info.Photoid))
                    {
                        dataList.Add(info);
                    }
                }
                CacheData["CusFileInfo"] = dataList;
            }

            string ServerFilePhoto=infoBll.GetServerPhoto();
            if (fileinfolist.Count > 0)
            {
                foreach (CusFileInfo item in fileinfolist)
                {
                    if (File.Exists(item.filepath))
                    {
                        FileInfo fileInfo = new FileInfo(item.filepath);
                        item.FileLength = fileInfo.Length;
                        item.PhotoServerFile = ServerFilePhoto;
                    }
                    else
                    {
                        infoBll.UpdatePhotoState(shopid, item.Photoid, 3);    
                    }
                }
            }
            WriteAnalyseLog.WriteLogFile(DateTime.Now + ":结束获取数据");
            return fileinfolist;
        }

        /// <summary>
        /// 更改状态
        /// </summary>
        /// <param name="outshopid"></param>
        /// <param name="photoid"></param>
        /// <returns></returns>
        public bool UpdateDownload(string outshopid, string photoid, string state)
        {
            return infoBll.UpdatePhotoState(Convert.ToInt32(outshopid), Convert.ToInt32(photoid), Convert.ToInt32(state));    //表示在服务品没有此图片
        }

        #endregion
    }
}
